package com.benhil.hrms.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.PersistenceException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.benhil.hrms.dao.IAccountDao;
import com.benhil.hrms.model.Account;

@Service
public class AccountService implements IAccountService {

	private final IAccountDao mAccountDao;
	
	@Autowired
	public AccountService(IAccountDao accountDao) {
		mAccountDao = accountDao;
	}

	@Override
	@Transactional(readOnly = true)
	public List<Account> getAccountList() {
		return mAccountDao.findAll();
	}

	@Override
	@Transactional(readOnly = false)
	public List<Account> create(Account data) {
		List<Account> newUsers = new ArrayList<Account>();	
		Account saved = mAccountDao.save(data);
		newUsers.add(saved);
		return newUsers;
	}

	@Override
	@Transactional(readOnly = false)
	public List<Account> update(Account data) {
		List<Account> newUsers = new ArrayList<Account>();		
		Account updated = mAccountDao.findOne(data.getId());
		if(updated == null){
			throw new PersistenceException();
		}
		
		// Update fields
		updated.setFirstName(data.getFirstName());
		updated.setAddress(data.getAddress());
		updated.setEmail(data.getEmail());
		
		Account saved = mAccountDao.save(updated);
		newUsers.add(saved);
		
		return newUsers;
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(Account data) {
		mAccountDao.delete(data.getId());		
	}
}
